package io.summer.auth.config;

import io.summer.auth.service.SysUserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ml
 * https://www.springcloud.cc/spring-security-zhcn.html#getting-started
 * https://docs.spring.io/spring-security/reference/servlet/architecture.html
 */
@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(myUserDetailsService())
      .passwordEncoder(passwordEncoder());
  }

  /**
   * 其实是默认设置
   */
  @Bean
  public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
  }

  @Bean
  protected UserDetailsService myUserDetailsService() {
    log.info("custom UserDetailsService...");
    return new SysUserServiceImpl();
  }

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/public/**");
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
      .antMatchers("/auth/internal/publicKey").permitAll()
      .anyRequest()
      .authenticated()
      //form login
//      .and()
//      .formLogin()
//      .and()
//      .httpBasic()
//      .and()
//      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//      .and()
//      .csrf().disable()
    ;
  }
}
